package online.misscl.lsy.util;

import cn.hutool.http.HttpRequest;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author
 * @Date 2022/8/1 10:06
 * @Description 利用Jwt生成token
 */

@Repository
public class JwtUtils {

    private static final String SECRET_KEY = "zxcvbnmasdfghjklqwertyuiop123456";//自定义密钥
    private static final long TOKEN_EXPIRE_TIME = 365 * 24 * 60 * 60 * 1000L * 100 ;//设置过期时间200h

    /**
     * 生成 jwt token
     */
    public static String generateToken(Integer userId, Integer auth){

        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);//SECRET_KEY自定义密钥
        // 设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");

//        TokenVo tokenVo = new TokenVo();
        // 生成 Token
        String token = JWT.create().withHeader(header)
                .withClaim("userId", userId)//自定义参数
                .withClaim("auth",auth)//自定义参数
                .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME)).sign(algorithm);//TOKEN_EXPIRE_TIME token过期时间 毫秒
        return token;
    }

    /**
     *  解析 jwt
     */
    public static Map<String, Claim> parseJwtTo(String token){
        Map<String, Claim> claims = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);//SECRET_KEY自定义密钥
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);//需要解析token
            claims = jwt.getClaims();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }

    /**@RequestHeader("token")
     * 验证token合法性
     */
    public static void verify(String token) throws Exception{

        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET_KEY )).build().verify(token);
            System.out.println(verify);
            String userId = verify.getClaim("userId").asString();
            String auth = verify.getClaim("auth").asString();

            System.out.println(userId);
            System.out.println(auth);
        }catch (TokenExpiredException e) {
            throw  new TokenExpiredException("令牌过期");
        } catch (JWTVerificationException e) {
            throw  new RuntimeException("令牌不正确");
        }catch (NullPointerException e){
            throw new NullPointerException("缺少token");
        }
    }

    /**
     * 获取当前登录id
     * @param httpServletRequest
     * @return
     */
    public static Integer getUserId(HttpServletRequest httpServletRequest){
        System.out.println(httpServletRequest.getHeader("Authorization"));
        Map<String, Claim> stringClaimMap = JwtUtils.parseJwtTo(httpServletRequest.getHeader("Authorization"));
        if(stringClaimMap == null){
            return 0;
        }
        return Integer.valueOf(String.valueOf(stringClaimMap.get("userId")));
    }

    public static void main(String[] args) {
        Map<String, Claim> stringClaimMap = parseJwtTo("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdXRoIjowLCJleHAiOjE2Nzg4OTI2NTksInVzZXJJZCI6MTl9.fash__NL7rKeUfGrcf75xNsHJrJqxyl8yyrVYgDhZBg");
        System.out.println(stringClaimMap.get("userId"));
    }

    /**
     * 获取当前登录auth
     * @param httpServletRequest
     * @return
     */
    public static Integer getAuth(HttpServletRequest httpServletRequest){
        Map<String, Claim> stringClaimMap = JwtUtils.parseJwtTo(httpServletRequest.getHeader("Authorization"));
        return Integer.valueOf(String.valueOf(stringClaimMap.get("auth")));
    }
}





//package online.misscl.lsy.util;
//
//import com.auth0.jwt.JWT;
//import com.auth0.jwt.algorithms.Algorithm;
//import com.auth0.jwt.exceptions.JWTVerificationException;
//import com.auth0.jwt.exceptions.TokenExpiredException;
//import com.auth0.jwt.interfaces.Claim;
//import com.auth0.jwt.interfaces.DecodedJWT;
//import io.jsonwebtoken.Claims;
//import io.jsonwebtoken.Jwts;
//import io.jsonwebtoken.SignatureAlgorithm;
//import org.springframework.stereotype.Repository;
//
//import java.util.Date;
//import java.util.HashMap;
//
//public class JwtUtils {
//
//    //过期时间--12小时
//    private static long expire = 43200;
//    //32位秘钥
//    private static String secret="zxcvbnmasdfghjklqwertyuiop123456";
//
//    //生成token
//    public static String generateToken(String userId,String auth){
//
//        Date now = new Date();
//        Date expiration = new Date(now.getTime()+1000*expire);
//
//
//        return Jwts.builder()
//                //设置头部信息
//                .setHeaderParam("type","JWT")
//                //载荷信息
////                .setSubject(userId)
//                .claim("id", userId)
//                .claim("auth", auth)
//                //生效时间
//                .setIssuedAt(now)
//                //过期时间
//                .setExpiration(expiration)
//                //签名算法
//                .signWith(SignatureAlgorithm.HS256,secret)
//                .compact();
//
//    }
//
//    //解析token
//    public static Claims getClaimsByToken(String token){
//
//        return Jwts.parser()
//                .setSigningKey(secret)
//                .parseClaimsJws(token)
//                .getBody();
//    }
//



